<?php

class DB{
    public static $tablename;
    public static $where='';
    public static $pdo;
    public static $stmt;
    public static $excuteData;
    public static $orderBy = '';

    public function __construct() {
        self::connect();
        self::setAttr();
    }

    /**
     * 数据库连接方法
     * @throws \Exception
     * @return void
     */
    public static function connect(){
        $DS = DIRECTORY_SEPARATOR;
        $config = require __DIR__."{$DS}..{$DS}config{$DS}database.php";
        $DBMS = $config["dbms"];
        $HOST = $config["host"];
        $DBNAME = $config["dbname"];
        $USERNAME = $config["user"];
        $PASSWORD = $config["password"];
        $DSN = "$DBMS:host=$HOST;dbname=$DBNAME;charset=utf8";
        try{
            self::$pdo = new PDO($DSN,$USERNAME,$PASSWORD);
        }catch(PDOException $e){
            throw new Exception("数据库连接错误:".$e->getMessage());
        }
    }

    /**
     * Summary of setAttr
     * @return void
     */
    private static function setAttr(){
        self::$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    }

    /**
     * wherer构造器
     * @param mixed $where
     * @return void
     */
    private function buildWhere($where,$AndOrNot='AND'){
        $oldWhere  = self::$where;
        if($where !== ''){
            if(strpos($oldWhere,'WHERE') === false){
                if($oldWhere !== ''){
                    $where = 'WHERE '.$oldWhere.' '.$AndOrNot.' '.$where;
                }else{
                    $where = 'WHERE '.$where;
                }
            }else{
                $where = $oldWhere.' '.$AndOrNot.' '.$where;
            }
            self::$where = $where;
        }
       
    }

    /**
     * Summary of table
     * @param mixed $tablename
     * @return DB
     */
    public static function table($tablename){
        self::$tablename = $tablename;
        return new self();
    }

    /**
     * select * from user where id=1 and  username=xx or where  createtime between  xxx  and  xxx  
     * @param array $condition
     * @return static
     */
    public function where(Array $condition,$AndOrNot='AND'){
        $where = "";
        if(!empty($condition)){
            foreach($condition as $key=>$value){
                if(strtoupper($value[1]) === "BETWEEN"){
                    $whereArray[] = "$value[0] $value[1] ? AND ?";
                    $excuteData[] = $value[2][0];
                    $excuteData[] = $value[2][1];
                }else if(strtoupper($value[1]) === "IN"){
                    $str = rtrim(str_repeat('?,',count($value[2])),',');
                    $whereArray[] = "$value[0] $value[1] ($str)";
                    foreach($value[2] as $v){
                        $excuteData[] = $v;
                    }
                }
                
                else{
                    $whereArray[] = "$value[0] $value[1] ?";
                    $excuteData[] = $value[2];
                }
            }
            if($AndOrNot !== 'NOT' && $AndOrNot !== 'ORNOT'){
                $where = implode(' '.$AndOrNot.' ',$whereArray);
            }else{
                if($AndOrNot == 'ORNOT'){
                    $where = implode(' '.'OR'.' ',$whereArray);
                }else{
                    $where = implode(' '.'AND'.' ',$whereArray);
                }
                $where = 'NOT ('.$where.')';
            }
            if(isset(self::$excuteData)){
                self::$excuteData = array_merge(
                    self::$excuteData,$excuteData
                );
            }else{
                self::$excuteData = $excuteData;
            }
        }
        $this->buildWhere($where,$AndOrNot);
        return $this;
        
    }

    /**
     * select * from user where username is  null 
     * @param mixed $str
     * @return static
     */
    public function whereNull($str){
        $where = "$str is null";
        $this->buildWhere($where);
        return $this;
    }

    /**
     * select * from user where username is not null 
     * @param mixed $str
     * @return static
     */
    public function whereNotNull($str){
        $where = "$str is not null";
        $this->buildWhere($where);
        return $this;
    }

    /**
     * select * from user where id=1 and  username=xx or where  createtime between  xxx  OR  xxx  
     * @param array $condition
     * @return DB
     */
    public function whereOr(Array $condition){

        return $this->where($condition,'OR');
    }

    /**
     * Summary of whereNot
     * @param array $condition
     * @return DB
     */
    public function whereOrNot(Array $condition){

        return $this->where($condition,'OrNot');
    }

    public function orderBy($parameter){
        self::$orderBy = "order by ".$parameter;
        return $this;
    }

    /**
     * 查询方法
     * @return void
     */
    public function select(){
        $sql = "SELECT * FROM"." ". self::$tablename." ".self::$where." ".self::$orderBy;
        self::$stmt = self::$pdo->prepare($sql);
        self::$excuteData ? self::$stmt->execute(self::$excuteData):self::$stmt->execute();
        $result = self::$stmt->fetchAll(PDO::FETCH_ASSOC);
        self::$stmt->closeCursor();
        return $result;
       

    }

}

  //DB::table("表名称")->where()->select;
    //DB::table("表名称")->where()->limit(10)->select;
    //DB::table("表名称")->where()->limit(10,20)->select;

 $result = DB::table("user")
 ->where([['createtime','between',["2024-12-03 08:00:00","2024-12-05 09:30:00"]]],'ORNOT')
 ->whereOr([['id','in',[2,3]]])
 ->whereNull('updatetime')
 ->orderBy("id DESC")->select();
//  $result = DB::table("user")->where([['id','in',[2,3]]])->select();
 var_dump($result);

